import { Component } from "@angular/core";
import {
  NavController,
  LoadingController,
  AlertController
} from "ionic-angular";
import { Storage } from "@ionic/storage";
import { HttpService } from "../../providers/http.service";
import { appConfig } from "../../providers/config";
import { CommonFunc } from "../../providers/commonFunc";
import { LoginPage } from "../login/login";

@Component({
  templateUrl: "changePwd.html",
  providers: [HttpService, CommonFunc]
})
export class ChangePwdPage {
  private oldpwd = "";
  private newpwd = "";
  private newpwd2 = "";
  constructor(
    public navCtrl: NavController,
    private storage: Storage,
    private httpService: HttpService,
    private alert: AlertController,
    private loading: LoadingController
  ) {

  }

  doSubmit() {

    this.storage.get('user').then(user => {
      let load = this.loading.create({
        spinner: appConfig.spinner,
        duration: appConfig.timeout
      });

      load.present();
      if (!this.oldpwd || !this.newpwd || !this.newpwd2) {
        this.alert
          .create({
            title: '错误',
            message: '请填写完整',
            buttons: ['确认'],
            enableBackdropDismiss: true
          })
          .present();
        return;
      }
      if (this.newpwd != this.newpwd2) {
          load.dismiss();
        this.alert
          .create({
            title: '错误',
            message: '两次输入的新密码不正确',
            buttons: ['确认'],
            enableBackdropDismiss:  true
          })
          .present();
        return;
      }

      //新密码与旧密码不能相同校验
        if (this.oldpwd == this.newpwd || this.oldpwd == this.newpwd2) {
            load.dismiss();
            this.alert
                .create({
                    title: '错误',
                    message: '新输入的密码不能和原密码相同！',
                    buttons: ['确认'],
                    enableBackdropDismiss:  true
                })
                .present();
            return;
        }

      let param = {
        id: user.id,
        oldpwd: this.oldpwd,
        newpwd: this.newpwd
      }
      this.httpService.updateUserPwd(param).subscribe(data => {
        load.dismiss();
        if (data.status == '200') {
          this.alert
            .create({
              title: '成功提示',
              message: '修改成功,请重新登录',
              buttons: ['确认'],
              enableBackdropDismiss: true
            })
            .present();
          this.navCtrl.setRoot(LoginPage);
        } else {
          this.alert
            .create({
              title: '错误',
              message: data.message,
              buttons: ['确认'],
              enableBackdropDismiss: true
            })
            .present();
          return;
        }
      });
    });

  }

  ionViewWillEnter() { }

  cancel() {
    this.navCtrl.pop();
  }
}
